from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, Date, Text
from sqlalchemy.orm import relation, backref

## todo: link activities to projects: depending on the type of project -> list different activities

Base = declarative_base()
metadata = Base.metadata

class Activity(Base):
    __tablename__ = "activity"

    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __init__(self, name):
        self.name = name

class Customer(Base):
    __tablename__ = "customer"

    id = Column(Integer, primary_key=True)
    name = Column(String)

    def __init__(self, name):
        self.name = name

class Project(Base):
    __tablename__ = "project"

    id = Column(Integer, primary_key=True)
    name = Column(String)
    customer_id = Column(Integer, ForeignKey("customer.id"))

    customer = relation(Customer, backref=backref('projects', order_by=id))

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "%s / %s" % (self.name, self.customer.name)

class Registration(Base):
    __tablename__ = "registration"

    id = Column(Integer, primary_key=True)
    duration = Column(Integer, default=0)
    when = Column(Date, default="now")
    description = Column(Text, default="")
    project_id = Column(Integer, ForeignKey("project.id"))
    activity_id = Column(Integer, ForeignKey("activity.id"))

    project = relation(Project, backref=backref('registrations', order_by=id))
    activity = relation(Activity, backref=backref('registrations', order_by=id))

    def __init__(self, duration):
        self.duration = duration

    def __str__(self):
        ## add activity
        return "%s / %s / %s" % (self.project.name, self.activity.name, self.duration)

    def __repr__(self):
        return "<Registration %d seconds>" % self.duration

if __name__ == '__main__':
    engine = create_engine("sqlite:///vcr.db", echo=True)
    metadata.create_all(engine)
